import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/hj_model/video_model.dart';
import 'package:xvideos/hj_utils/date_time_util.dart';
import 'package:xvideos/hj_utils/player_util.dart';
import 'package:xvideos/tools_base/global_store/store.dart';
import 'package:video_player/video_player.dart';

import '../../../alert_business/video/video_buy_alert.dart';
import '../../../alert_business/video/video_buy_bottom_sheet.dart';
import '../../../alert_business/video/vip_dailog.dart';
import '../../../hj_utils/free_play_count_manager.dart';
import '../../pre_sale/pre_sale_provider.dart';

class LongVideStatus {
  bool isNeedVip = false;
  bool isNeedBuy = false;
  String statusDesc = "";
}

class DetailTopRightView extends StatefulWidget {
  final VideoModel? videoModel;
  final VideoPlayerController? controller;
  final Function(bool)? buyCallback; // true Buy, false vip

  const DetailTopRightView({
    super.key,
    this.videoModel,
    this.controller,
    this.buyCallback,
  });

  @override
  State<StatefulWidget> createState() {
    return _DetailTopRightViewState();
  }
}

class _DetailTopRightViewState extends State<DetailTopRightView> {
  VideoModel? get videoModel => widget.videoModel;

  VideoPlayerController? get controller => widget.controller;

  bool get isCartoon => widget.videoModel?.videoType == 1;

  int get freeCount {
    return FreePlayCountManager().playCount?.watchCount ?? 0;
  }

  bool isShowImply = true; //  已享VIP免费特权, 3S后自动隐藏
  Timer? _timer;
  int _timeCount = 0;

  @override
  void initState() {
    super.initState();
  }

  void beginTimerEvent() {
    if (_timer == null) {
      _timer = Timer.periodic(Duration(seconds: 1), (_) {
        _timeCount++;
        if (_timeCount >= 3) {
          isShowImply = false;
          _timer?.cancel();
          if (mounted) setState(() {});
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!isShowImply) {
      return SizedBox();
    }
    LongVideStatus status = longVideoStatusDesc(widget.videoModel);
    String statusDesc = status.statusDesc;
    if (statusDesc == "已享VIP免费特权") {
      beginTimerEvent();
      return Container(
        padding: const EdgeInsets.fromLTRB(12, 3, 12, 3),
        decoration: BoxDecoration(color: Color(0x99000000)),
        child: Text(
          statusDesc,
          style: TextStyle(color: Colors.white, fontSize: 12),
        ),
      );
    }
    return SizedBox();
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }
}

class VideoStatusView extends StatefulWidget {
  final VideoModel? model;
  final VideoPlayerController? controller;
  final Function? onBuyEvent;

  const VideoStatusView({super.key, this.model, this.controller, this.onBuyEvent});

  @override
  State<VideoStatusView> createState() => _VideoStatusViewState();
}

class _VideoStatusViewState extends State<VideoStatusView> {
  int get freeCount {
    return FreePlayCountManager().playCount?.watchCount ?? 0;
  }

  bool get isCartoon => widget.model?.videoType == 1;

  @override
  Widget build(BuildContext context) {
    if (widget.model == null) return SizedBox.shrink();
    LongVideStatus status = longVideoStatusDesc(widget.model);
    bool isNeedVip = status.isNeedVip;
    bool isNeedBuy = status.isNeedBuy;
    String statusDesc = status.statusDesc;
    if (statusDesc.contains("跳过预览") && widget.model?.videoType == 1) {
      return SizedBox(); // 预览,动漫不显示
    }
    if (statusDesc == "已享金币视频免费特权" && widget.model?.videoType == 1) {
      return SizedBox(); // // 动漫不显示这个
    }
    //已享VIP免费特权 用 DetailTopRightView 来处理, 在右上角, 3秒后消失
    if (statusDesc.isNotEmpty && statusDesc != "已享VIP免费特权") {
      return GestureDetector(
        onTap: () async {
          widget.onBuyEvent?.call();
          if (presaleProvider.isOpen) {
            if (isNeedVip) {
              widget.controller?.pause();
              if (presaleProvider.isOpen && presaleProvider.hasLimit == false) {
                await Get.dialog(const VipDialog(presale: true));
              }
            } else if (isNeedBuy) {
              widget.controller?.pause();
              bool hasPresaleActivity = presaleProvider.isOpen && !presaleProvider.isPayAll();
              if (!hasPresaleActivity) return;
              var result =
              await Get.bottomSheet(VideoBuyBottomSheet(videoM: widget.model!, presale: hasPresaleActivity));
              if (result == true || result == 1 || result == 2) {
                widget.model?.vidStatus?.hasPaid = true;
                widget.model?.mediaInfo?.mediaStatus?.hasPaid = true;
                if (mounted) setState(() {});
              }
            }
          }
        },
        child: Container(
          padding: EdgeInsets.fromLTRB(12, 3, 12, 3),
          decoration: BoxDecoration(color: Color(0x99000000)),
          child: Text(
            statusDesc,
            style: TextStyle(color: Colors.white, fontSize: 12),
          ),
        ),
      );
    }
    return SizedBox();
  }

  @override
  void dispose() {
    super.dispose();
  }
}

/*
会员权益：
普通会员： VIP长视频  VIP抖音 社区帖子VIP 图集VIP 小说VIP ACGVIP
高级会员：VIP+金币视频（长视频，抖音），社区VIP帖子。图集金币 小说 金币 ACG 。 暗网视频和社区金币帖子除外
超级会员： 全网通 包含暗网+社区金币帖子
黄游单独购买
* */
LongVideStatus longVideoStatusDesc(VideoModel? model) {
  if (model == null) return LongVideStatus();
  // pk 打榜视频,不显示免费次数
  int freeCount = FreePlayCountManager().playCount?.watchCount ?? 0;
  final isVIP = globalStore.isVIP();
  LongVideStatus status = LongVideStatus();
  String statusDesc = "";
  if (globalStore.isMe(model.publisher?.uid)) {
    return status; // 自己发布的视频
  }else if (model.freeArea == true) {
    statusDesc = "免费视频";
  } else if (!isVIP && freeCount >= 0 && model.originCoins == 0 && FreePlayCountManager().canFreePlay(model)) {
    statusDesc = "免费视频剩余${freeCount + 1}次";
  } else if (isVIP && model.originCoins == 0) {
    //已享VIP免费特权 用 DetailTopRightView 来处理, 在右上角, 3秒后消失
    statusDesc = "已享VIP免费特权";
  } else if (model.vidStatus?.hasPaid == true) {
    statusDesc = "已购买完整版";
  } else if (!isVIP && model.originCoins == 0 && FreePlayCountManager().canFreePlay(model) == true) {
    statusDesc = ""; // 免费次数内的视频观看的视频,重复观看,是可以免费看的
  } else if (coinFreePrivilegeCount(model) >= 0) {
    statusDesc = "免费金币观影数剩余: ${coinFreePrivilegeCount(model)}次";
  }else if ((model.originCoins ?? 0) > 0 && model.vidStatus?.hasPaid != true && globalStore.isAWVIP()) {
    statusDesc = "已享金币视频免费特权"; //"${widget.model?.originCoins}金币跳过预览";
  } else if ((model.originCoins ?? 0) > 0 && model.vidStatus?.hasPaid != true && globalStore.isVIPTwoLevel()) {
    statusDesc = "已享金币视频免费特权"; //"${widget.model?.originCoins}金币跳过预览";
  } else  if (globalStore.isVIP() && DateTimeUtil.calTime3(globalStore.getMe()?.goldVideoFreeExpire) > 0 && (model.originCoins ?? 50) <= 50) {
    statusDesc = "已享金币视频免费特权";
  } else  if (globalStore.isVIP() && (model.originCoins ?? 0) >0 && model.coins == 0) {
    statusDesc = "已享金币视频免费特权";
  } else if (!isVIP && model.originCoins == 0 && FreePlayCountManager().canFreePlay(model) != true) {
    statusDesc = "跳过预览";
    status.isNeedVip = true;
  }else if ((model.originCoins ?? 0) > 0) {
    statusDesc = "${model.coins}金币 跳过预览";
    status.isNeedBuy = true;
  } else {
    status.isNeedVip = true;
    statusDesc = "跳过预览";
  }
  status.statusDesc = statusDesc;
  return status;
}

int coinFreePrivilegeCount(VideoModel? model) {
  // 权益免费观看次数(仅限金币视频)
  if (model?.isCoinVideo() != true) {
    // 非金币视频
    return -1;
  }
  if (model?.freeArea == true) {
    return -1;
  }
  // vip金币视频 免看
  if (globalStore.isVIP() && model?.coins == 0) {
    return -1;
  } else {
    if (model?.videoType == 1) return -1; // 动漫视频不享受金币免次数权益
    return presaleProvider.coinVideoFreeCount;
  }
}
